//
//  SegementScrollView.m
//  WuJieLive
//
//  Created by iMac on 2017/11/21.
//  Copyright © 2017年 zhk. All rights reserved.
//

#define btnWidth 50
#define Space (self.width - 120 - 3 * btnWidth) / 2
#import "SegementScrollView.h"

@implementation SegementScrollView

-(instancetype)initWithFrame:(CGRect)frame andtitleArray:(NSArray *)array;
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupViewWithArray:array];
    }
    return self; 
}
-(void)setupViewWithArray:(NSArray *)array
{
    self.userInteractionEnabled = YES;
    self.backgroundColor = [UIColor whiteColor];
    
    for (int i = 0; i < array.count; i ++) {
        self.segementBtn = [[UIButton alloc]init];
        [self.segementBtn setTitle:array[i] forState:(UIControlStateNormal)];
        [self.segementBtn setTitleColor:TextAssistColor forState:(UIControlStateNormal)];
        self.segementBtn.titleLabel.font = FontSize(14);
        [self.segementBtn setTitleColor:MainColor forState:(UIControlStateSelected)];
        self.segementBtn.tag = 3000 + i;
        [self addSubview:self.segementBtn];
        
        [self.segementBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.left.offset(60 + i * (Space + btnWidth));
            make.width.offset(btnWidth);
            make.bottom.offset(-5);
        }];
        
        if (self.segementBtn.tag == 3000) {
            self.segementBtn.selected = YES;
        }
        [self.segementBtn addTarget:self action:@selector(segementBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(60, self.height - 3, btnWidth, 3)];
    self.lineView.backgroundColor = MainColor;
    [self addSubview:self.lineView];
}

- (void)segementBtnAction:(UIButton *)sender
{
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            ((UIButton *)subView).selected = NO;
        }
        sender.selected = YES;
    }
    [UIView animateWithDuration:0.2 animations:^{
        CGRect frame = self.lineView.frame;
        frame.origin.x = 60 + (sender.tag - 3000) * (Space + btnWidth);
        self.lineView.frame = frame;
    }];
    
    if (self.selectedBlock) {
        self.selectedBlock(sender.tag - 3000);
    }
}


@end
